package com.xpec.c4.db.usertype;

import java.util.Arrays;

import org.hibernate.HibernateException;

import com.ms.db.usertype.BasicToString;
import com.xpec.c4.db.util.CodecTool;

/**
 * 把整形数组(String[])转换为String<br>
 * 使用指定的分隔符，默认为";"
 * 
 * @author Bany
 * 
 */
public class ArrayStringToString extends BasicToString {

	/**
	 * 
	 */
	private static final long serialVersionUID = 958960629773801996L;

	@Override
	public int[] sqlTypes() {
		return CLOB_TYPES;
	}

	@Override
	public Class<?> returnedClass() {
		return String[].class;
	}

	@Override
	public boolean equals(Object x, Object y) throws HibernateException {
		if (x != null && y != null) {
			String[] xArray = (String[]) x;
			String[] yArray = (String[]) y;
			if (xArray.length != yArray.length)
				return false;
			for (int i = 0; i < xArray.length; i++) {
				String s1 = xArray[i];
				String s2 = yArray[i];
				if(s1==null && s2 ==null){
					continue;
				}
				if((s1!=null && s2 ==null)||(s1==null && s2!=null)){
					return false;
				}
				if (!s1.equals(s2))
					return false;
			}
			return true;
		}
		return false;
	}

	@Override
	protected String assemble(Object obj) {
		String[] stringArray = (String[]) obj;
		StringBuffer strBuf = new StringBuffer();
		strBuf.append(stringArray.length).append(SPLITTER);
		for (int i = 0; i < stringArray.length; i++) {
			CodecTool.append(strBuf,stringArray[i],SPLITTER);
		}
		
		if(strBuf.length() > 0)
		{
			strBuf.setLength(strBuf.length()-1);
		}

		return strBuf.toString();
	}

	@Override
	protected String[] parse(String value) {
		if(value==null){
			return null;
		}
		int index = 0;
		String[] strs = CodecTool.split(value, SPLITTER);
		int len = Integer.valueOf(strs[index++]);
		String[] newStr=new String[len];
		if(len>0){
			newStr=Arrays.copyOfRange(strs, 1, strs.length);
		}
		return newStr;
	}

}
